package com.xingfudazi.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.xingfudazi.app.domain.AppMemberInfo;
import com.xingfudazi.app.dto.CarNumDto;
import com.xingfudazi.app.dto.MemberAvatar;
import com.xingfudazi.app.mapper.AppMemberInfoMapper;
import com.xingfudazi.app.service.IAppMemberInfoService;
import com.xingfudazi.app.service.ImUserService;
import com.xingfudazi.app.service.domain.WxRequestService;
import com.xingfudazi.app.util.CarUtil;
import com.xingfudazi.app.util.NFtoGMapping;
import com.xingfudazi.app.vo.AppMatchMemberVO;
import com.xingfudazi.common.enums.DBDataStatus;
import com.xingfudazi.common.exception.ExceptionEnum;
import com.xingfudazi.common.utils.DateUtils;
import com.xingfudazi.common.utils.JSONUtil;
import com.xingfudazi.common.utils.SecurityUtils;
import com.xingfudazi.common.utils.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.util.*;
import java.util.stream.Collectors;


/**
 * 会员-个人信息Service业务层处理
 *
 * @author ruoyi
 * @date 2024-06-21
 */
@Service
public class AppMemberInfoServiceImpl extends ServiceImpl<AppMemberInfoMapper, AppMemberInfo> implements IAppMemberInfoService {
    @Autowired
    private AppMemberInfoMapper appMemberInfoMapper;

    @Autowired
    private ImUserService imUserService;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 查询会员-个人信息
     *
     * @param id 会员-个人信息主键
     * @return 会员-个人信息
     */
    @Override
    public AppMemberInfo selectAppMemberInfoById(Long id) {
        return appMemberInfoMapper.selectById(id);
    }

    /**
     * 查询会员-个人信息列表
     *
     * @param appMemberInfo 会员-个人信息
     * @return 会员-个人信息
     */
    @Override
    public List<AppMemberInfo> selectAppMemberInfoList(AppMemberInfo appMemberInfo) {
        LambdaQueryWrapper<AppMemberInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(AppMemberInfo::getCreateTime);
        return appMemberInfoMapper.selectList(wrapper);
    }

    /**
     * 新增会员-个人信息
     *
     * @param appMemberInfo 会员-个人信息
     * @return 结果
     */
    @Override
    public int insertAppMemberInfo(AppMemberInfo appMemberInfo) {
        return appMemberInfoMapper.insert(appMemberInfo);
    }

    /**
     * 修改会员-个人信息
     *
     * @param appMemberInfo 会员-个人信息
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateAppMemberInfo(AppMemberInfo appMemberInfo) {
        String birthday = appMemberInfo.getBirthday();
        if (StringUtils.isNotBlank(birthday)) {
            Date date = DateUtils.parseDate(birthday);
            appMemberInfo.setZodiac(AppMemberInfo.computeZodiac(date));
            appMemberInfo.setStar(AppMemberInfo.computeConstellation(date));
        }

        AppMemberInfo infoMapper = appMemberInfoMapper.selectById(appMemberInfo.getId());
        String province = appMemberInfo.getProvince();
        String city = appMemberInfo.getCity();
        // 更新时如果 之前没有 code 并且当前有 province 和 city 生成 code
        if (StringUtils.isBlank(infoMapper.getCode()) && StringUtils.isNotBlank(province) && StringUtils.isNotBlank(city)) {
            CarNumDto numDto = CarUtil.carNum(province, city);
            String code = numDto.getCode();
            String randomCode = CarUtil.generateString();
            appMemberInfo.setCode(code + randomCode);
        }

        if (!Objects.equals(infoMapper.getHead(), appMemberInfo.getHead()) || !Objects.equals(infoMapper.getBlood(), appMemberInfo.getBlood())) {
            // 如果是空或者为 null 默认值为X
            if (StringUtils.isBlank(appMemberInfo.getHead())) {
                appMemberInfo.setHead("x");
            }
            if (StringUtils.isBlank(appMemberInfo.getBlood())) {
                appMemberInfo.setBlood("x");
            }

            String url = "https://fourcalc.ccyit.net/fourcalc-v2/source/Yun/YunFour/calc";
            Map<String, Object> params = new HashMap<>(1);
            params.put("corp_id", "123456");
            params.put("corp_secret_id", "bd7dc75a8d315d7d11d57e208996624d");
            params.put("client_name", appMemberInfo.getNickName());
            params.put("birthday", appMemberInfo.getBirthday());
            params.put("head", appMemberInfo.getHead());
            params.put("blood", appMemberInfo.getBlood());
            Map<?, ?> result = this.post(url, params);
            // 对返回结果进行处理
            String four = (String) result.get("four");
            appMemberInfo.setFourCode(four);
        }

        appMemberInfo.setNid(null);
        appMemberInfo.setCreateTime(null);
        appMemberInfo.setUpdateTime(null);
        int update = appMemberInfoMapper.updateById(appMemberInfo);
        if (update == 1) {
            imUserService.updateByAppMemberInfo(appMemberInfoMapper.selectById(appMemberInfo.getId()));
        }
        return update;
    }

    /**
     * 删除会员-个人信息信息
     *
     * @param id 会员-个人信息主键
     * @return 结果
     */
    @Override
    public int deleteAppMemberInfoById(Long id) {
        AppMemberInfo appMemberInfo = new AppMemberInfo();
        appMemberInfo.setDelFlag(DBDataStatus.DELETED.getCode());
        appMemberInfo.setId(id);
        return appMemberInfoMapper.updateById(appMemberInfo);
    }

    @Override
    public void init(String phone, String nickName, Long nid) {
        AppMemberInfo appMemberInfo = new AppMemberInfo();
        appMemberInfo.setId(nid);
        appMemberInfo.setNid(nid);
        appMemberInfo.setPhone(phone);
        appMemberInfo.setNickName(nickName);
        this.insertAppMemberInfo(appMemberInfo);
    }

    @Override
    public MemberAvatar queryMemberAvatar(Long nid) {
        List<MemberAvatar> memberAvatars = queryMemberAvatar(Lists.newArrayList(nid));
        if (memberAvatars.isEmpty()) {
            return null;
        }
        return memberAvatars.get(0);
    }

    @Override
    public List<MemberAvatar> queryMemberAvatar(List<Long> nids) {
        LambdaQueryWrapper<AppMemberInfo> wrapper = new LambdaQueryWrapper<>();
        // ID = nid
        wrapper.in(AppMemberInfo::getId, nids);
        wrapper.select(AppMemberInfo::getNid, AppMemberInfo::getAvatar, AppMemberInfo::getNickName);

        return this.appMemberInfoMapper.selectList(wrapper).stream().map(appMemberInfo -> {
                    MemberAvatar memberAvatar = new MemberAvatar();
                    memberAvatar.setNid(appMemberInfo.getNid());
                    memberAvatar.setNickName(appMemberInfo.getNickName());
                    memberAvatar.setAvatar(appMemberInfo.getAvatar());
                    return memberAvatar;
                })
                .collect(Collectors.toList());
    }

    @Override
    public List<AppMemberInfo> turn(Integer pageSize, Long lastId, String search, String type) {
        return this.appMemberInfoMapper.trun(pageSize, lastId, search, type);
    }

    @Override
    public List<AppMatchMemberVO> match(String four) {
        Long userId = SecurityUtils.getUserId();
        LambdaQueryWrapper<AppMemberInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.isNotNull(AppMemberInfo::getFourCode);
        wrapper.ne(AppMemberInfo::getNid, userId);
        wrapper.last("ORDER BY RAND() LIMIT 4");

        List<AppMemberInfo> memberInfoList = this.appMemberInfoMapper.selectList(wrapper);

        List<AppMatchMemberVO> resultList = new ArrayList<>();
        memberInfoList.forEach(m -> {
            String url = "https://fourcalc.ccyit.net/fourcalc-v2/source/Yun/YunFour/match";
            Map<String, Object> params = new HashMap<>(1);
            params.put("corp_id", "123456");
            params.put("corp_secret_id", "bd7dc75a8d315d7d11d57e208996624d");
            params.put("four1", four);
            params.put("four2", m.getFourCode());
            Map<?, ?> result = this.post(url, params);
            String sunCode = (String) result.get("sun_code");
            String moonCode = (String) result.get("moon_code");
            List<String> matchResult = NFtoGMapping.getGValues(sunCode, moonCode);
            AppMatchMemberVO res = new AppMatchMemberVO();
            try {
                // 复制 m 的属性到 res
                BeanUtils.copyProperties(m, res);

                res.setMatchResult(matchResult);
                resultList.add(res);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        return resultList;
    }

    public static void main(String[] args) {
        System.out.println(System.currentTimeMillis());
    }

    Map<?, ?> post(String url, Map<String, Object> params) {
        // 请求头
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        HttpEntity<String> request = new HttpEntity<>(JSONUtil.toJsonStr(params), headers);
        Map<?, ?> result = restTemplate.postForObject(url, request, Map.class);

        if (result == null || "0".equals(result.get("errcode"))) {
            throw  ExceptionEnum.WX_REQUEST_EXCEPTION.unwrap();
        }
        return result;
    }
}
